import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Progress, Typography, Space, Table, Tag } from 'antd';
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip, Legend } from 'recharts';
import {
  EnvironmentOutlined,
  SettingOutlined,
  DatabaseOutlined,
  RiseOutlined,
  ExperimentOutlined,
  SignalFilled,
} from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import PermissionDemo from '../components/PermissionDemo';
import { sampleAPI, deviceAPI, dataAPI } from '../services/api';
import { formatTimestamp } from '../utils/formatters';
import dayjs from 'dayjs';

const { Title, Text } = Typography;

const Dashboard = () => {
  const { t } = useTranslation();
  const [dashboardData, setDashboardData] = useState({
    sampleCount: 0,
    deviceCount: 0,
    dataCount: 0,
    recentData: [],
    allDataCount: 0,
    deviceStatus: [],
    deviceTypes: [],
    temperatureData: [],
    allTempDataCount: 0,
  });
  const [loading, setLoading] = useState(true);
  const [nextRefreshTime, setNextRefreshTime] = useState(null);


  // 获取仪表盘数据
  const fetchDashboardData = async () => {
    setLoading(true);
    try {
      // 安全的API调用，每个调用都有独立的错误处理
      const fetchSafely = async (apiCall, defaultValue = { data: { list: [], total: 0 } }) => {
        try {
          return await apiCall();
        } catch (error) {
          console.warn('API调用失败，使用默认值:', error.message);
          return defaultValue;
        }
      };

      // 并行获取优化的数据，避免超时
      const [samplesRes, devicesRes, deviceDataRes, tempDataRes] = await Promise.all([
        fetchSafely(() => sampleAPI.getSampleList({ pageNo: 1, pageSize: 1 })), // 只查1条获取总数
        fetchSafely(() => deviceAPI.getDeviceList({})), // 查询全部设备用于类型统计
        fetchSafely(() => dataAPI.getDeviceDataList({
          pageNo: 1,
          pageSize: 20,
          pageOrderName: 'id',
          pageOrderBy: 'desc'
        })), // 最新20条设备数据，按ID降序
        fetchSafely(() => dataAPI.getDeviceTmpRHList({
          pageNo: 1,
          pageSize: 15,
          pageOrderName: 'simpletime',
          pageOrderBy: 'desc'
        })), // 最新15条温湿度数据，按时间降序
      ]);

      const samples = samplesRes?.data?.list || [];
      const devices = devicesRes?.data?.list || [];
      const deviceData = deviceDataRes?.data?.list || [];
      const tempData = tempDataRes?.data?.list || [];

      // 不再需要计算在线设备数量

      // 设备状态统计
      const deviceStatusStats = devices.reduce((acc, device) => {
        const typeMap = { 0: '普通设备', 1: '4G设备', 2: '网关设备' };
        const typeName = typeMap[device.type] || '未知';
        acc[typeName] = (acc[typeName] || 0) + 1;
        return acc;
      }, {});

      // 获取设备类型列表
      const deviceTypes = Object.keys(deviceStatusStats);

      // 计算数据总量 = 设备数据总量 + 温湿度数据总量
      const deviceDataTotal = deviceDataRes?.data?.total || deviceDataRes?.data?.totalCount || deviceData.length;
      const tempDataTotal = tempDataRes?.data?.total || tempDataRes?.data?.totalCount || tempData.length;
      const totalDataCount = deviceDataTotal + tempDataTotal;

      setDashboardData({
        sampleCount: samplesRes?.data?.total || samplesRes?.data?.totalCount || samples.length,
        deviceCount: devices.length, // 使用实际设备数量进行统计
        dataCount: totalDataCount, // 设备数据 + 温湿度数据总量
        recentData: deviceData.slice(0, 8), // 用于显示表格
        allDataCount: deviceDataTotal, // 全部设备数据条数
        deviceStatus: Object.entries(deviceStatusStats).map(([type, count]) => ({ type, count })),
        deviceTypes: deviceTypes, // 设备类型列表
        temperatureData: tempData.slice(0, 8), // 实时温湿度数据前8条（用于表格显示）
        allTempDataCount: tempDataTotal, // 全部温湿度数据总条数
      });
    } catch (error) {
      console.error('获取仪表盘数据失败:', error);
      // 设置默认数据以确保界面正常显示
      setDashboardData({
        sampleCount: 0,
        deviceCount: 0,
        dataCount: 0,
        recentData: [],
        allDataCount: 0,
        deviceStatus: [],
        deviceTypes: [],
        temperatureData: [],
        allTempDataCount: 0,
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDashboardData();
  }, []);

  // 自动刷新功能 - 每10分钟刷新一次
  useEffect(() => {
    // 设置下次刷新时间
    const setRefreshTime = () => {
      const nextTime = new Date();
      nextTime.setMinutes(nextTime.getMinutes() + 10);
      setNextRefreshTime(nextTime);
    };

    setRefreshTime();

    // 设置定时器，每10分钟执行一次
    const interval = setInterval(() => {
      console.log('自动刷新仪表盘数据...');
      fetchDashboardData();
      setRefreshTime();
    }, 10 * 60 * 1000); // 10分钟 = 10 * 60 * 1000毫秒

    // 清理定时器
    return () => {
      clearInterval(interval);
    };
  }, []);

  // 统计数据配置
  const stats = [
    {
      title: '样地总数',
      value: dashboardData.sampleCount,
      icon: <EnvironmentOutlined style={{ fontSize: 24, color: '#1890ff' }} />,
      color: '#1890ff',
      suffix: '个',
    },
    {
      title: '设备总数',
      value: dashboardData.deviceCount,
      icon: <SettingOutlined style={{ fontSize: 24, color: '#52c41a' }} />,
      color: '#52c41a',
      suffix: '台',
    },
    {
      title: '监测点位',
      value: dashboardData.sampleCount + dashboardData.deviceCount,
      icon: <RiseOutlined style={{ fontSize: 24, color: '#faad14' }} />,
      color: '#faad14',
      suffix: '个',
    },
    {
      title: '数据总量',
      value: dashboardData.dataCount,
      icon: <DatabaseOutlined style={{ fontSize: 24, color: '#f5222d' }} />,
      color: '#f5222d',
      suffix: '条',
    },
  ];

  // 设备类型分布数据（用于饼图）
  const getDeviceTypePieData = () => {
    const deviceStatus = dashboardData.deviceStatus || [];
    const totalDevices = dashboardData.deviceCount;

    if (totalDevices === 0 || deviceStatus.length === 0) {
      return [
        { name: '暂无设备', value: 1, color: '#d9d9d9', percentage: '100.0' }
      ];
    }

    // 设备类型颜色映射
    const typeColorMap = {
      '普通设备': '#1890ff',
      '4G设备': '#52c41a',
      '网关设备': '#faad14',
      '未知设备': '#f5222d'
    };

    return deviceStatus.map(item => ({
      name: item.type,
      value: item.count,
      color: typeColorMap[item.type] || '#722ed1',
      percentage: totalDevices > 0 ? ((item.count / totalDevices) * 100).toFixed(1) : '0.0'
    })).filter(item => item.value > 0);
  };

  const deviceTypePieData = getDeviceTypePieData();

  // 最近数据表格列定义
  const recentDataColumns = [
    {
      title: '设备编号',
      dataIndex: 'code',
      key: 'code',
      width: 80,
    },
    {
      title: '电压（V）',
      dataIndex: 'voltage',
      key: 'voltage',
      width: 100,
      render: (value) => value ? `${(value / 100).toFixed(2)}` : '-',
    },
    {
      title: '信号强度（dBm）',
      dataIndex: 'rssi',
      key: 'rssi',
      width: 150,
      render: (value) => {
        const color = value > -60 ? '#52c41a' : value > -80 ? '#faad14' : '#f5222d';
        return <Tag color={color}>{value}</Tag>;
      },
    },
    {
      title: '温度（°C）',
      dataIndex: 'tmp',
      key: 'tmp',
      width: 100,
      render: (value) => value ? `${(value / 100).toFixed(1)}` : '-',
    },
    {
      title: '时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      render: (updatedAt) => formatTimestamp(updatedAt),
    },
  ];

  // 温湿度数据表格列
  const tempHumidityColumns = [
    {
      title: '设备',
      dataIndex: 'code',
      key: 'code',
      width: 80,
    },
    {
      title: '批次',
      dataIndex: 'batch',
      key: 'batch',
      width: 100,
    },
    {
      title: '温度（°C）',
      dataIndex: 'temp',
      key: 'temp',
      width: 100,
      render: (value) => value ? `${(value / 100).toFixed(1)}` : '-',
    },
    {
      title: '湿度（%）',
      dataIndex: 'humi',
      key: 'humi',
      width: 100,
      render: (value) => value ? `${(value / 100).toFixed(1)}` : '-',
    },
    {
      title: '时间',
      dataIndex: 'simpletime',
      key: 'simpletime',
      render: (timestamp) => formatTimestamp(timestamp),
    },
  ];

  return (
    <div>
      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <Title level={2}>数据总览</Title>
            <Text type="secondary">树径管理系统 - 实时监控数据 (显示最新数据)</Text>
          </div>
        </div>

        {/* 统计卡片 */}
        <Row gutter={[24, 24]}>
          {stats.map((stat, index) => (
            <Col xs={24} sm={12} lg={6} key={index}>
              <Card
                hoverable
                loading={loading}
                style={{
                  borderRadius: 16,
                  border: 'none',
                  background: `linear-gradient(135deg, ${stat.color}08 0%, ${stat.color}03 100%)`,
                  boxShadow: '0 8px 24px rgba(0,0,0,0.12)',
                  transition: 'all 0.3s ease',
                  position: 'relative',
                  overflow: 'hidden',
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.transform = 'translateY(-5px)';
                  e.currentTarget.style.boxShadow = '0 12px 32px rgba(0,0,0,0.18)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.transform = 'translateY(0)';
                  e.currentTarget.style.boxShadow = '0 8px 24px rgba(0,0,0,0.12)';
                }}
                styles={{
                  body: {
                    padding: '24px',
                    position: 'relative',
                    zIndex: 2,
                  }
                }}
              >
                {/* 装饰背景 */}
                <div
                  style={{
                    position: 'absolute',
                    top: -20,
                    right: -20,
                    width: 80,
                    height: 80,
                    background: `linear-gradient(135deg, ${stat.color}20, ${stat.color}10)`,
                    borderRadius: '50%',
                    zIndex: 1,
                  }}
                />

                <Statistic
                  title={
                    <Space style={{ marginBottom: 8 }}>
                      <div style={{
                        padding: '8px',
                        background: `linear-gradient(135deg, ${stat.color}, ${stat.color}cc)`,
                        borderRadius: '8px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                      }}>
                        {React.cloneElement(stat.icon, {
                          style: { fontSize: 18, color: 'white' }
                        })}
                      </div>
                      <Text style={{
                        fontWeight: '600',
                        fontSize: '14px',
                        color: '#333',
                      }}>
                        {stat.title}
                      </Text>
                    </Space>
                  }
                  value={stat.value}
                  suffix={stat.suffix}
                  valueStyle={{
                    color: stat.color,
                    fontSize: 32,
                    fontWeight: 'bold',
                    textShadow: '0 2px 4px rgba(0,0,0,0.1)',
                  }}
                  style={{
                    textAlign: 'left',
                  }}
                />
              </Card>
            </Col>
          ))}
        </Row>

        <Row gutter={[24, 24]}>
          {/* 设备类型分析 */}
          <Col xs={24} lg={12}>
            <Card
              title={
                <Space>
                  <SettingOutlined style={{ color: '#1890ff' }} />
                  设备类型分析
                </Space>
              }
              loading={loading}
              style={{
                borderRadius: 12,
                border: 'none',
                boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
                height: '100%',
                minHeight: 320,
              }}
            >
              <Space direction="vertical" style={{ width: '100%' }} size="large">
                <div style={{ outline: 'none' }}>
                  <Text strong style={{ marginBottom: 16, display: 'block' }}>设备类型分布</Text>
                  <div style={{ outline: 'none', border: 'none' }}>
                    <ResponsiveContainer width="100%" height={250}>
                      <PieChart
                        style={{ outline: 'none' }}
                        onMouseDown={(e) => e.preventDefault()}
                      >
                        <defs>
                          {deviceTypePieData.map((entry, index) => (
                            <linearGradient key={`gradient-${index}`} id={`gradient-${index}`} x1="0" y1="0" x2="1" y2="1">
                              <stop offset="0%" stopColor={entry.color} stopOpacity={1} />
                              <stop offset="100%" stopColor={entry.color} stopOpacity={0.7} />
                            </linearGradient>
                          ))}
                        </defs>
                        <Pie
                          data={deviceTypePieData}
                          cx="50%"
                          cy="50%"
                          innerRadius={50}
                          outerRadius={90}
                          paddingAngle={3}
                          dataKey="value"
                          animationBegin={0}
                          animationDuration={1000}
                          stroke="rgba(255,255,255,0.8)"
                          strokeWidth={2}
                          onMouseEnter={(data, index) => {
                            // 移除默认的focus样式
                            if (document.activeElement) {
                              document.activeElement.blur();
                            }
                          }}
                        >
                          {deviceTypePieData.map((entry, index) => (
                            <Cell
                              key={`cell-${index}`}
                              fill={`url(#gradient-${index})`}
                              style={{
                                filter: 'drop-shadow(2px 2px 4px rgba(0,0,0,0.1))',
                                cursor: 'pointer',
                                outline: 'none',
                                border: 'none',
                                boxShadow: 'none'
                              }}
                              onFocus={(e) => e.target.blur()}
                              tabIndex={-1}
                            />
                          ))}
                        </Pie>
                        <Tooltip
                          formatter={(value, name, props) => [
                            <span style={{ fontWeight: 'bold', color: props.color }}>
                              {value}台 ({props.payload.percentage}%)
                            </span>,
                            name
                          ]}
                          contentStyle={{
                            backgroundColor: 'rgba(255,255,255,0.95)',
                            border: 'none',
                            borderRadius: '8px',
                            boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
                            backdropFilter: 'blur(10px)'
                          }}
                          labelStyle={{ color: '#666', fontSize: '14px', fontWeight: '500' }}
                        />
                        <Legend
                          verticalAlign="bottom"
                          height={50}
                          iconType="circle"
                          wrapperStyle={{ fontSize: '12px', paddingTop: '10px' }}
                          formatter={(value, entry) => (
                            <span style={{
                              color: entry.color,
                              fontWeight: '500',
                              textShadow: '0 1px 2px rgba(0,0,0,0.1)'
                            }}>
                              {value} ({entry.payload.percentage}%)
                            </span>
                          )}
                        />
                      </PieChart>
                    </ResponsiveContainer>
                  </div>
                </div>
              </Space>
            </Card>
          </Col>

          {/* 数据统计 */}
          <Col xs={24} lg={12}>
            <Card
              title={
                <Space>
                  <SignalFilled style={{ color: '#f5222d' }} />
                  数据采集统计
                </Space>
              }
              loading={loading}
              style={{
                borderRadius: 12,
                border: 'none',
                boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
                height: '100%',
                minHeight: 320,
              }}
            >
              <Space direction="vertical" style={{ width: '100%' }} size="large">
                <div>
                  <Statistic
                    title="设备数据总量"
                    value={dashboardData.allDataCount}
                    suffix="条"
                    valueStyle={{ color: '#1890ff' }}
                  />
                </div>
                <div>
                  <Statistic
                    title="温湿度数据总量"
                    value={dashboardData.allTempDataCount}
                    suffix="条"
                    valueStyle={{ color: '#52c41a' }}
                  />
                </div>
                <div>
                  <Statistic
                    title={
                      <Space direction="vertical" size={0}>
                        <span>设备类型</span>
                        <Text type="secondary" style={{ fontSize: 12 }}>
                          {dashboardData.deviceTypes.length > 0
                            ? `(${dashboardData.deviceTypes.join('、')})`
                            : '(暂无数据)'}
                        </Text>
                      </Space>
                    }
                    value={dashboardData.deviceStatus.length}
                    suffix="种"
                    valueStyle={{ color: '#faad14' }}
                  />
                </div>
              </Space>
            </Card>
          </Col>


        </Row>

        <Row gutter={[24, 24]}>
          {/* 温湿度监控 */}
          <Col xs={24} lg={12}>
            <Card
              className="dashboard-card"
              title={
                <Space>
                  <ExperimentOutlined style={{ color: '#faad14' }} />
                  温湿度监控
                </Space>
              }
              loading={loading}
              style={{
                borderRadius: 12,
                border: 'none',
                boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
              }}
            >
              <div className="dashboard-table-scroll">
                <Table
                  columns={tempHumidityColumns}
                  dataSource={dashboardData.temperatureData}
                  rowKey="id"
                  size="small"
                  pagination={false}
                  scroll={{ x: 'max-content' }}
                />
              </div>
            </Card>
          </Col>

          {/* 最近设备数据 */}
          <Col xs={24} lg={12}>
            <Card
              className="dashboard-card"
              title={
                <Space>
                  <DatabaseOutlined style={{ color: '#52c41a' }} />
                  最新设备数据
                </Space>
              }
              loading={loading}
              style={{
                borderRadius: 12,
                border: 'none',
                boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
              }}
            >
              <div className="dashboard-table-scroll">
                <Table
                  columns={recentDataColumns}
                  dataSource={dashboardData.recentData}
                  rowKey="id"
                  size="small"
                  pagination={false}
                  scroll={{ x: 'max-content' }}
                  style={{ fontSize: 12 }}
                />
              </div>
            </Card>
          </Col>
        </Row>
        {/* 权限演示 */}
        <PermissionDemo />

      </Space>
    </div>
  );
};

export default Dashboard;
